import { listAccountOrganization, updateAccount } from '@/services/api/api-admin-account';
import { getWxmpAccountPage } from '@/services/api/api-admin-wxmp-account';
import { ActionType, ProFormRadio, ProList } from '@ant-design/pro-components';
import ProForm, {
  DrawerForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { Checkbox, Descriptions, message, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import AddAccountOrganization from './AddAccountOrganization';
import EditAccountOrganization from './EditAccountOrganization';

interface EditAccountProps {
  account: AdminAccountData.Account;
  onRefurbish: () => void;
}
const EditAccount: React.FC<EditAccountProps> = ({ account, onRefurbish }) => {
  const formRef = useRef<ProFormInstance>();
  const userRef = useRef<ActionType>();

  const [saveAccountOrganizations, setSaveAccountOrganizationsState] = useState<
    AdminAccountBo.AccountOrganizationSaveBo[]
  >([]);

  const [selectedWxmpAccountRowKeys, setSelectedWxmpAccountKeysState] = useState<React.Key[]>([]);

  // 定义一个状态来跟踪所选项
  const [selectedItemId, setSelectedItemId] = useState(account.loginCombineId);

  /**
   * 根据key加载组织详情
   * @param key
   */
  const loadListAccountOrganizationData = async () => {
    const response = await listAccountOrganization({ accountId: account.id });
    if (response.code === 0) {
      const values = response.data.map((item) => {
        return {
          id: item.id,
          organizations: item.organizationCascaders.map((item1) => ({
            organizationId: item1.id,
            organizationName: item1.name,
          })),
          organizationCascaderIds: item.organizationCascaders.map((item) => item.id),
          roles: item.roles.map((item) => ({
            roleId: item.id,
            roleName: item.name,
          })),
          marks: item.marks,
          seq: item.seq,
          loginCombineId: selectedItemId,
          state: item.state,
        };
      });
      setSaveAccountOrganizationsState(values);
    }
  };

  const onselectlOginId = (e: any) => {
    const checkedItemId = e.target.value;
    // 检查所选项是否已选中
    if (checkedItemId === selectedItemId) {
      // 如果已选中，则清除选择  ,不让清除
      // setSelectedItemId(null);
    } else {
      // 如果未选中，则更新所选项
      setSelectedItemId(checkedItemId);
    }
  };

  return (
    <DrawerForm
      key="edit_account_drawer"
      title="编辑用户"
      drawerProps={{
        destroyOnClose: true,
      }}
      trigger={<a key="edit_account">编辑</a>}
      formRef={formRef}
      initialValues={{
        name: account.name,
        phone: account.phone,
        isActivation: account.isActivation,
        state: account.state,
      }}
      onOpenChange={(open) => {
        if (open) {
          loadListAccountOrganizationData();
        } else {
          // setSaveAccountOrganizationsState([]);
        }
      }}
      onFinish={async (values) => {
        if (values.pinCode !== undefined && values.pinCode.length !== 1) {
          values.pinCode = values.pinCode[0];
        } else {
          values.pinCode = undefined;
        }

        if (saveAccountOrganizations.length === 0) {
          message.warning('请添加关联单位');
          return false;
        }

        const value = saveAccountOrganizations.map((item) => {
          const organization = item.organizations[item.organizations.length - 1];
          return {
            organizationId: organization.organizationId,
            organizationCascaderIds: item.organizations.map((item) => item.organizationId),
            organizationCascaderNames: item.organizations.map((item) => item.organizationName),
            roleIds: item.roles.map((item) => item.roleId),
            marks: item.marks,
            seq: item.seq,
            state: item.state,
            isDefaultLogin: selectedItemId === item.id,
          };
        });

        const response = await updateAccount({
          id: account.id,
          loginCombineId: selectedItemId,
          organizations: value,
          ...values,
        });
        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="name"
          label="账号"
          rules={[{ required: true, message: '请输入账号' }]}
        />
        <ProFormText
          width="md"
          name="phone"
          label="电话"
          rules={[{ required: true, message: '请输入电话' }]}
        />
      </ProForm.Group>
      {account.isWechatWxmpSubscribe === 0 && (
        <ProForm.Group>
          <ProFormSelect
            name="pinCode"
            label="关联微信公众号用户身份识别码"
            showSearch
            fieldProps={{
              mode: 'multiple',
              allowClear: true,
              showSearch: true,
              showArrow: false,
              open: false,
              optionFilterProp: 'children',
              filterOption: (input: any, option: any) => {
                console.log(option);
                // return option.options.filter((item: any) => item.label.includes(input));
                return option.label.includes(input);
              },
              listHeight: 500,
              style: {
                width: 488,
              },
            }}
            addonAfter={
              <DrawerForm
                title="关联微信公众号用户列表"
                trigger={<a key="activeSaveAssign">点击添加</a>}
                autoFocusFirstInput
                drawerProps={{
                  destroyOnClose: true,
                }}
                onVisibleChange={(visible: boolean) => {
                  if (visible) {
                    const pinCode = formRef.current?.getFieldValue('pinCode') as [];
                    if (pinCode) {
                      setSelectedWxmpAccountKeysState([...pinCode]);
                    }
                  }
                }}
                submitter={false}
              >
                <ProTable<AdminAccountData.WxmpAccount>
                  ghost
                  rowSelection={{
                    selectedRowKeys: selectedWxmpAccountRowKeys,
                    type: 'radio',
                    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                      setSelectedWxmpAccountKeysState(selectedRowKeys);
                      formRef.current?.setFieldsValue({
                        pinCode: selectedRowKeys,
                      });
                    },
                  }}
                  tableAlertRender={false}
                  columns={[
                    {
                      title: '身份识别码',
                      key: 'pinCode',
                      dataIndex: 'pinCode',
                    },
                    {
                      title: '关注时间',
                      key: 'createdTime',
                      dataIndex: 'createdTime',
                      hideInSearch: true,
                      width: 200,
                    },
                  ]}
                  request={async (params = {}) => {
                    const response = await getWxmpAccountPage({
                      ...params,
                    });
                    return Promise.resolve({
                      data: response.data.data,
                      total: response.data.total,
                      success: response.code === 0,
                    });
                  }}
                  rowKey="id"
                  tableLayout="fixed"
                  dateFormatter="string"
                  headerTitle={false}
                  bordered
                  options={{
                    search: {
                      name: 'pinCode',
                      onSearch: (keyword: string) => {
                        setSelectedWxmpAccountKeysState([]);
                        formRef.current?.setFieldsValue({
                          pinCode: undefined,
                        });
                        return true;
                      },
                    },
                  }}
                  search={false}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    defaultPageSize: 50,
                  }}
                />
              </DrawerForm>
            }
          />
        </ProForm.Group>
      )}
      {account.isActivation === 0 && (
        <ProForm.Group>
          <ProFormRadio.Group
            name="isActivation"
            label="激活"
            options={[
              {
                label: '启用',
                value: 1,
              },
              {
                label: '禁用',
                value: 0,
              },
            ]}
          />
        </ProForm.Group>
      )}
      <ProForm.Group>
        <ProFormRadio.Group
          name="state"
          label="状态"
          options={[
            {
              label: '启用',
              value: 1,
            },
            {
              label: '禁用',
              value: 0,
            },
          ]}
        />
      </ProForm.Group>
      <ProList<AdminAccountBo.AccountOrganizationSaveBo>
        ghost
        rowKey="id"
        headerTitle="关联单位"
        actionRef={userRef}
        toolBarRender={() => [
          <AddAccountOrganization
            key="add_account_organization"
            onRefurbish={(value: AdminAccountBo.AccountOrganizationSaveBo) => {
              const isContained = saveAccountOrganizations.some(
                (item) =>
                  item.organizationCascaderIds.toString() ===
                  value.organizationCascaderIds.toString(),
              );

              if (isContained) {
                message.warning('请勿添加重复单位！');
                return false;
              }

              saveAccountOrganizations.push(value);

              setSaveAccountOrganizationsState(saveAccountOrganizations);
              userRef.current?.reset();
              return true;
            }}
          />,
        ]}
        dataSource={saveAccountOrganizations}
        showActions="hover"
        editable={{
          onSave: async (key, record, originRow) => {
            console.log(key, record, originRow);
            return true;
          },
        }}
        metas={{
          title: {
            render: (text, row) => {
              console.log('=========', row.state);

              return (
                <div>
                  <Descriptions>
                    <Descriptions.Item label="单位">
                      <Space size={0}>
                        {row.organizations.map((item) => {
                          return (
                            <Tag color={row.state === 1 ? 'blue' : 'red'} key={item.organizationId}>
                              {item.organizationName}
                            </Tag>
                          );
                        })}
                      </Space>
                      <Checkbox
                        value={row.id}
                        onChange={onselectlOginId}
                        checked={selectedItemId === row.id}
                      >
                        设为默认登陆
                      </Checkbox>
                    </Descriptions.Item>
                  </Descriptions>
                  {row?.marks && row?.marks.length > 0 && (
                    <Descriptions>
                      <Descriptions.Item label="标记">
                        <Space size={0}>
                          {row?.marks?.map((item) => (
                            <Tag key={item} color="orange">
                              {item}
                            </Tag>
                          ))}
                        </Space>
                      </Descriptions.Item>
                    </Descriptions>
                  )}
                </div>
              );
            },
          },
          description: {
            render: (text, row) => {
              return (
                <Space direction="vertical" size={0} style={{ display: 'flex' }}>
                  <Descriptions>
                    <Descriptions.Item label="角色">
                      <Space size={6} wrap>
                        {row.roles.map((item) => (
                          <Tag key={item.roleId}>{item.roleName}</Tag>
                        ))}
                      </Space>
                    </Descriptions.Item>
                  </Descriptions>
                  {/* </ProCard> */}
                </Space>
              );
            },
          },
          actions: {
            render: (text, row, index, action) => [
              <EditAccountOrganization
                key="edit_account_organization"
                marks={row.marks}
                organizationCascaderIds={row.organizationCascaderIds}
                roles={row.roles}
                seq={saveAccountOrganizations[index].seq}
                state={saveAccountOrganizations[index].state}
                onRefurbish={(value: AdminAccountBo.AccountOrganizationSaveBo) => {
                  saveAccountOrganizations.forEach((item) => {
                    if (
                      item.organizationCascaderIds.toString() ===
                      value.organizationCascaderIds.toString()
                    ) {
                      item.roles = value.roles;
                      item.marks = value.marks;
                      item.seq = value.seq;
                      item.state = value.state;
                    }
                  });
                  setSaveAccountOrganizationsState(saveAccountOrganizations);
                  userRef.current?.reset();
                  return true;
                }}
              />,
              <a
                key="link"
                onClick={(e) => {
                  if (selectedItemId === row.id.toString()) {
                    message.error('请勿删除默认登陆选项,如需删除请更换默认登陆单位');
                    return false;
                  }
                  setSaveAccountOrganizationsState(
                    saveAccountOrganizations.filter(
                      (item) =>
                        item.organizationCascaderIds.toString() !==
                        row.organizationCascaderIds.toString(),
                    ),
                  );
                }}
              >
                删除
              </a>,
            ],
          },
        }}
      />
    </DrawerForm>
  );
};
export default EditAccount;
